<?php

namespace App\Repositories\Eloquent\Mgt;


use Illuminate\Container\Container as App;
use App\Repositories\Eloquent\Repository;
use App\Repositories\Eloquent\Mgt\ActivityRepository as Activity;
use App\Repositories\Eloquent\Mgt\BookRepository as Book;
use App\Repositories\Eloquent\Biz\BorrowRepository as Borrow;
use App\Repositories\Eloquent\Biz\TrackRepository as Track;
use App\Repositories\Eloquent\Biz\RecordRepository as Record;
use App\Repositories\Eloquent\Biz\SummaryRepository as Summary;
use App\Repositories\Eloquent\Biz\GiftRepository as Gift;
use Auth, Hash, DB;

class UserRepository extends Repository
{

    protected $activity, $book, $borrow, $record, $track, $summary, $gift;
    /**
     * @param App
     */
    public function __construct(App $app, Activity $activity, Book $book,
            Borrow $borrow, Track $track, Record $record, Summary $summary, Gift $gift)
    {
        parent::__construct($app);

        $this->activity = $activity;

        $this->book = $book;

        $this->borrow = $borrow;

        $this->track = $track;

        $this->record = $record;

        $this->summary = $summary;

        $this->gift = $gift;
    }

    /**
     * 指定模型名称
     *
     * @return mixed
     */
    function model()
    {
        return 'App\Models\Mgt\User';
    }


    /**
     * [用户列表]
     * @param  string $query  [账号或ID号]
     * @param  [type] $type   [用户类型:读者/志愿者]
     * @param  [type] $source [注册类型:后台注册/网络注册]
     * @return [type]         [description]
     */
    public function index($query = '', $type = null, $source = null)
    {
        //匹配到全数字，按账号查找
        if (preg_match('/^\d+$/i', $query)) {
            if(strlen($query) == 5){
                $result = $this->model->with('summary')
                    ->when($type, function($query, $type){
                        return $query->where('type', $type);
                    })
                    ->when($source, function($query, $source){
                        return $query->where('source', $source);
                    })
                    ->where('account', $query)
                    ->orderBy('id','desc');
            }
            else{
                $result = $this->model->with('tracks','summary')
                    ->when($type, function($query, $type){
                        return $query->where('type', $type);
                    })
                    ->when($source, function($query, $source){
                        return $query->where('source', $source);
                    })
                    ->where('mobile','like',"%$query%")
                    ->orderBy('id','desc');
            }

        }
        //未匹配到数字，按姓名查找
        else {
            $result = $this->model->with('tracks','summary')
                ->when($type, function($query, $type){
                    return $query->where('type', $type);
                })
                ->when($source, function($query, $source){
                    return $query->where('source', $source);
                })
                ->where('name','like',"%$query%")
                ->orderBy('id','desc');
        }

        return $result;
    }

    public function view($id)
    {
        return $this->model->find($id);
    }


    public function show($id)
    {
        if( strlen($id) == 5){
            $user = $this->findBy('account', $id);
        }
        else{
            $user = $this->find($id);
        }

        if (!$user)
            return $this->responseFail(404,'账号信息不正确');

        $user->dwz = DWZ.$user->account;

        return $user;
    }


    public function store($request)
    {
        DB::beginTransaction();

        try{
            $user = $this->create([
                'name'      => $request->name,
                'account'   => \App\Models\Mgt\Util::generate( $this->model->max('account') ),
                'password'  => Hash::make(DEFAULT_PASSWORD),
                'mobile'    => $request->mobile,
                'idcard'    => $request->idcard,
                'gender'    => $request->gender,
                'birthday'  => date('Y-m-d',strtotime( $request->birthday)),
                'stay'      => is_null($request->stay) ? 0:1,
                'poor'      => is_null($request->poor) ? 0:1,
                'school_id' => is_null($request->school) ? 1:$request->school,
                'branch_id' => Auth::guard('admin')->user()->branch->id,
                'memo'      => $request->memo,
                'created_at' => time(),
                'type'      => $request->type,
                'source'    => $request->source,
            ]);
            if ($result = !!$user) {
                    $user->summary()->create([
                    'type'          =>$user->type,
                    'updated_at'    =>time()
                ]);
            }
        DB::commit();

        return $this->responseSuccess('添加账号成功', $user,
                    $request->type==1?route('user.index'):route('volunteer.index'));

        } catch (Exception $e) {

            DB::rollback();

            return $this->responseFail(500,'添加账号失败');
        }

    }


    public function renew($request, $id)
    {
        DB::beginTransaction();

        try {
            $result = $this->update([
                'name'      => $request->name,
                'mobile'    => $request->mobile,
                'idcard'    => $request->idcard,
                'gender'    => $request->gender,
                'birthday'  => date('Y-m-d',strtotime( $request->birthday)),
                'stay' => is_null($request->stay) ? 0:$request->stay,
                'poor' => is_null($request->poor) ? 0:$request->poor,
                'school_id' => is_null($request->school) ? 1:$request->school,
                'memo'      => $request->memo,
            ], $id);

            DB::commit();

            return $this->responseSuccess('更新账号信息成功');

        } catch (Exception $e) {

            DB::rollback();

            return $this->responseFail(500,'更新账号信息失败');
        }
    }

    /**
     * 查询结果格式转换(多用户)
     * @param  [type] $activity [description]
     * @param  [type] $users    [description]
     * @return [type]           [description]
     */
    public function transforms(\App\Models\Mgt\Activity $activity, $users)
    {
        $enabled = \App\Models\Mgt\Activity::enabled();

        $data = $users->all();

        $data = collect($data)->map(function ($users) use($activity, $enabled) {

            //$users->mobile = substr_replace($users->mobile, '****', 3, 4);

            $users->signed = $users->signed($activity->id, $users->type);

            $users->awarded = $users->signed($activity->id, 3);

            $users->enabled = $enabled;

            return $users;
        });

        return $users;
    }

    /**
     * 查询结果格式转换(单用户)
     * @param  [type] $activity [description]
     * @param  [type] $user     [description]
     * @return [type]           [description]
     */
    public function transform($activity, $user)
    {
        if( !!$user ){


            $user->birthday = date('Ymd', strtotime($user->birthday));

            //$user->mobile = substr_replace($user->mobile, '****', 3, 4);

            $user->signed = $user->signed($activity->id, $user->type);

            $user->awarded = $user->signed($activity->id, 3);

            $user->dwz = DWZ.$user->account;

        }

        return $user;
    }

    /**
     * 签到与积分奖励
     * @param  [type] $activity [活动]
     * @param  [type] $user     [用户]
     * @param  [type] $type     [用户类型]
     * @return [type]           [description]
     */
    public function checkin($request)
    {
        $user = $this->show($request->uid);
        //需传递activity，不一定是当前活动，用于补签
        $activity = $this->activity->show($request->aid);

        $type = $request->type;

        //$type=3 奖励积分
        if( $type == \App\Models\Biz\Track::TRACK_TYPE_AWARD){
            if ( !$user->signed($activity->id, $user->type) )
                return $this->responseFail(403,'未签到不能获得积分奖励');
        }

        if( $user->signed($activity->id, $type))
            return $this->responseFail(403, '不能重复获取积分');

        DB::beginTransaction();

        try{
            $this->track->set($user, $activity, $type);

            //签到时，积分值默认为用户类型，阅读者1，志愿者2
            $point = $this->record->set($user, $activity, $user->type, $type);

            $this->summary->set($user, $type, $point);

            DB::commit();

            $result = array_merge($user->summary->toArray(), $activity->summary());

            return $this->responseSuccess($type == \App\Models\Biz\Track::TRACK_TYPE_AWARD?'积分奖励成功':'签到成功', $result);
        }
        catch (Exception $e){

            DB::rollBack();

            return $this->responseFail(500, $type == \App\Models\Biz\Track::TRACK_TYPE_AWARD?'积分奖励失败':'签到失败');
        }

    }


    /**
     * [借书]
     * @param  [type] $user     [description]
     * @param  [type] $activity [description]
     * @param  [type] $book     [description]
     * @return [type]           [description]
     */
    public function borrow($request)
    {
        if(!isset($request->bid) || empty($request->bid))
            return $this->responseFail(403, '请选择需要借阅的书籍');

        $record = $this->borrow->occupied($request);

        if(!!$record)
            return $this->responseFail(403,'重复借阅！');

        $user = $this->show($request->uid);

        $activity = $this->activity->show($request->aid);

        $book = $this->book->show($request->bid);

        DB::beginTransaction();

        try{
            $borrow = $this->borrow->set($user, $activity, $book);

            $this->book->status($book, \App\Models\Mgt\Book::BOOK_STATUS_BORROWED);

            $this->summary->set($user, $request->type);

            DB::commit();

            $result = array_merge(
                $user->toArray(), $book->toArray(),$borrow->toArray()
            );

            return $this->responseSuccess('借阅登记成功', $result);
        }
        catch (Exception $e){

            DB::rollBack();

            return $this->responseFail(500,'借阅登记失败');
        }
    }


    /**
     * [还书]
     * @param  [type] $request [description]
     * @return [type]          [description]
     */
    public function return($request)
    {
        $borrow = $this->borrow->show($request->id);

        if( $borrow->status == \App\Models\Biz\Borrow::BORROW_STATUS_RETURNED )
            return $this->responseFail(403,'书籍已归还');

        DB::beginTransaction();

        try{

            $this->borrow->rset($borrow, $request->activity);

            $this->book->status($borrow->book, \App\Models\Mgt\Book::BOOK_STATUS_UNBORROW);

            $this->summary->set($borrow->user, $request->type);

            DB::commit();

            $result = array_merge(
                $borrow->user->summary->toArray(),
                $request->activity->summary()
            );

            return $this->responseSuccess('还书成功', $result);

        }
        catch (Exception $e){

            DB::rollBack();

            return $this->responseFail(500,'还书失败');
        }

    }

    /**
     * [兑换礼品]
     * @param  [type] $request [uid,gid]
     * @return [type]          [description]
     */
    public function exchange($request)
    {
        $user = $this->show($request->uid);

        $gift = $this->gift->show($request->gid);

        if( $user->summary->points < $gift->price)
            return $this->responseFail(405,'兑换积分不足');

        DB::beginTransaction();

        try{
            $exchange = \App\Models\Biz\Exchange::create([
                'uid'       => $user->id,
                'account'   => $user->account,
                'gift_id'   => $gift->id,
                'code'      => $gift->code,
                'name'    => $gift->name,
                'image'      => $gift->image,
                'number'        => 1,
                'price'        => $gift->price,
                'total'        => $gift->price,
                'date'        => time(),
            ]);

            if( !!$exchange){

                $point = $this->record->set($user, $request->activity, $gift->price, 9, FLAG_CREDIT);

                $this->summary->set($user, 9, $point);

            }

            DB::commit();

            $result = array_merge(
                $user->toArray(),
                $user->summary->toArray()
            );

            return $this->responseSuccess('兑换礼品成功', $result);

        }
        catch (Exception $e){

            DB::rollBack();

            return $this->responseFail(500,'兑换礼品失败');
        }

    }

    /**
     * [签到统计]
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function statistics($request)
    {
        $date_begin = strtotime($request->date_begin);
        $date_end = strtotime($request->date_end);

        $result = \App\Models\Track::select(DB::raw('count(uid) as total, uid'))
                ->where('type',$request->type)
                ->whereBetween('date', array($date_begin, $date_end))
                ->groupBy('uid')
                ->orderBy('total','desc')
                ->paginate(50);
        $data = collect($result->all())->map(function ($result){

            $result->user = \App\Models\User::find($result->uid);

        });

        return $result;
    }


}